package myJs.cps.project

import myJs.Implicits._
import myJs.api.Api
import myJs.cps.BootstrapTableCp.Column
import myJs.cps.{BootstrapTableCp, Style}
import myJs.myPkg.reactBootstrap.{OverlayTrigger, Popover}
import myJs.tool.Pojo.{CheckboxSearch, ExportData, NumericSearch, TextSearch}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.ReactElement
import slinky.web.html._
import typings.csstype.csstypeStrings
import upickle.default.{reader, writeJs}

import scala.collection.immutable.SeqMap
import scala.scalajs.js

/** Created by yz on 21/1/2022
  */
@react object AbundanceBulkCp {

  type Props = Unit

  val component = FunctionalComponent[Props] { props =>
    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (columns, setColumns) = useState(List.empty[Column])

    object FTool {
      def getTableRs = {
        Api.getFileData("abundance/Abundance_hbulk.csv").map { response =>
          response
        }
      }
      def refreshTableB = () => {
        getTableRs.map { response =>
          val curDatas = response.array
          val map = response.map
          val basicColumns = map.map { case (k, v) =>
            val searchKind = v match {
              case x if List("_pval", "_OR", "_Freq").exists(y => x.endsWith(y)) => NumericSearch
              case "Phenotype" => CheckboxSearch
              case x
                  if List("Mean_Fraction(%)", "Mean_Rela_Fraction(%)", "Log2FC", "Pval", "Pval_adjust").contains(x) =>
                NumericSearch
              case _ => TextSearch
            }
            val title = v
            val fmt = FTool.tbFmt(k)
            val comVF = FTool.comVFmt(v)
            val optionMap = searchKind match {
              case CheckboxSearch =>
                curDatas
                  .map { dict =>
                    dict(k)
                  }
                  .distinct
                  .optionMap
              case _ => SeqMap[String, String]()
            }
            Column(
              field = k,
              title = title,
              operable = true,
              searchKind = searchKind,
              formatter = fmt,
              comVF = comVF,
              optionMap = optionMap
            )
          }.toList
          setColumns(basicColumns)
          val datas = curDatas.map(x => writeJs(x).transform(reader[ujson.Obj]))
          setDatas(datas)
        }
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case _ => span(v.myStr)()
        }
      }

      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.myStr
        }
      }

    }

    useEffect(
      () => {
        FTool.refreshTableB()
      },
      List()
    )

    val exportDatas = List(
      ExportData("CSV", href = s"${Api.apiUrl}/gepLiver/tool/downloadFile?fileName=abundance/Abundance_hbulk.csv")
    )

    div(
      style := Style(),
      h5(
        style := Style(marginBottom = 15, fontSize = 16, marginTop = 15),
        id := "abundanceBulk",
        "Abundance Analysis-Bulk ", {
          val popover: ReactElement = Popover(id = "popover-basic")(
            Popover.Title("Note"),
            Popover.Content(
              "Phenotype abundance and enrichment analysis for human bulk RNA-seq data based on the deconvolution with the single cell matrices."
            )
          )
          OverlayTrigger(
            placement = "right",
            trigger = js.Array("focus", "hover"),
            overlay = popover
          )(
            span(
              a(`type` := "button", i(className := "fas fa-info-circle"))
            )
          )
        }
      ),
      BootstrapTableCp(
        columns = columns,
        datas = datas,
        pageList = List(10, 25, 50),
        pageSize = 10,
        showExport = true,
        exportData = exportDatas,
        selectColumnEnabled = true,
        showColumnNames = List("Lineage", "Cell_Type", "Phenotype", "Mean_Fraction(%)", "Log2FC", "Pval")
      )
    )

  }

  object STool {

    val myBtn =
      Style(cursor = csstypeStrings.pointer, marginBottom = 10, paddingTop = 3, paddingBottom = 3, marginRight = 15)

  }

}
